package cn.chiship.bs.api.biz.service.impl;

import cn.chiship.bs.api.biz.entity.*;
import cn.chiship.bs.api.biz.mapper.MemberUserMapper;
import cn.chiship.bs.api.biz.mapper.OrderHeaderItemMapper;
import cn.chiship.bs.api.biz.mapper.OrderHeaderMapper;
import cn.chiship.bs.api.biz.mapper.ProductProductMapper;
import cn.chiship.bs.api.biz.pojo.dto.OrderCreateDto;
import cn.chiship.bs.api.biz.pojo.dto.OrderProductDto;
import cn.chiship.bs.api.biz.service.OrderHeaderService;
import cn.chiship.sdk.core.base.BaseResult;
import cn.chiship.sdk.core.exception.custom.BusinessException;
import cn.chiship.sdk.core.id.SnowflakeIdUtil;
import cn.chiship.sdk.core.util.StringUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;

@Service
public class OrderHeaderServiceImpl extends BaseServiceImpl<OrderHeader, OrderHeaderExample> implements OrderHeaderService {

    @Resource
    private OrderHeaderMapper orderHeaderMapper;
    @Resource
    private OrderHeaderItemMapper orderHeaderItemMapper;

    @Resource
    private MemberUserMapper memberUserMapper;

    @Resource
    private ProductProductMapper productProductMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResult createOrder(OrderCreateDto orderCreateDto) {
        String orderId = SnowflakeIdUtil.generateStrId();
        List<OrderProductDto> orderProductDtos = orderCreateDto.getOrderProductDtos();
        if (orderProductDtos.isEmpty()) {
            return BaseResult.error("订单商品明细不能为空！");
        }
        MemberUser memberUser = memberUserMapper.selectByPrimaryKey(orderCreateDto.getUserId());
        if (StringUtil.isNull(memberUser)) {
            return BaseResult.error("不存在的用户");
        }
        String orderName = null;
        BigDecimal totalPrice = BigDecimal.ZERO;
        for (OrderProductDto orderProductDto : orderProductDtos) {
            String productId = orderProductDto.getProductId();
            int number = orderProductDto.getNumber();
            ProductProduct productProduct = productProductMapper.selectByPrimaryKey(productId);
            if (productProduct.getProductInventoryNumber() == 0) {
                throw new BusinessException("库存不足");
            }
            totalPrice = totalPrice.add(productProduct.getProductShopPrice().multiply(BigDecimal.valueOf(number)));
            orderName = productProduct.getProductName();

            productProduct.setSalesVolume(productProduct.getSalesVolume() + number);
            productProduct.setProductInventoryNumber((productProduct.getProductInventoryNumber() - number));
            productProductMapper.updateByPrimaryKeySelective(productProduct);


            OrderHeaderItem orderHeaderItem = new OrderHeaderItem();
            orderHeaderItem.setId(SnowflakeIdUtil.generateStrId());
            orderHeaderItem.setGmtCreated(System.currentTimeMillis());
            orderHeaderItem.setGmtModified(System.currentTimeMillis());
            orderHeaderItem.setIsDeleted(Byte.valueOf("0"));
            orderHeaderItem.setOrderId(orderId);
            orderHeaderItem.setProductId(productProduct.getId());
            orderHeaderItem.setProductName(productProduct.getProductName());
            orderHeaderItem.setProductNumber(number);
            orderHeaderItem.setProductPrice(productProduct.getProductShopPrice());
            orderHeaderItem.setProductImg(productProduct.getProductImg());
            orderHeaderItemMapper.insertSelective(orderHeaderItem);
        }
        if (orderProductDtos.size() > 1) {
            orderName += "等" + orderProductDtos.size() + "件商品";
        }


        OrderHeader orderHeader = new OrderHeader();
        orderHeader.setId(orderId);
        orderHeader.setGmtCreated(System.currentTimeMillis());
        orderHeader.setGmtModified(System.currentTimeMillis());
        orderHeader.setIsDeleted(Byte.valueOf("0"));
        orderHeader.setOrderName(orderName);
        orderHeader.setOrderDate(System.currentTimeMillis());
        orderHeader.setOrderStatus(Byte.valueOf("0"));
        orderHeader.setAddress(orderCreateDto.getAddress());
        orderHeader.setUserRealName(memberUser.getRealName());
        orderHeader.setUserPhone(memberUser.getMobile());
        orderHeader.setUserId(StringUtil.getString(memberUser.getId()));
        orderHeader.setGrandTotal(totalPrice);
        orderHeaderMapper.insertSelective(orderHeader);
        return BaseResult.ok();
    }

    @Override
    public BaseResult changeStatus(String orderId, Byte status) {
        OrderHeader orderHeader = orderHeaderMapper.selectByPrimaryKey(orderId);
        if (StringUtil.isNull(orderHeader)) {
            return BaseResult.error("订单不存在!");
        }
        orderHeader.setOrderStatus(status);
        return super.updateByPrimaryKeySelective(orderHeader);
    }
}
